const repair = (i) => {
	return i < 10 ? '0' + i : i
}

/**
 * 获取当前日期（默认）、时间、星期
 * type：date、time、week
 * sub：相差天数，-1前一天 1后一天
 * time：时间基准
 */
const getNow = (type, sub, time) => {
	let str, date, y, M, d, H, m, s, w
	if (!time) {
		date = new Date()
	} else {
		date = new Date(time)
	}
	if (sub) {
		date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * sub)
	}
	y = date.getFullYear()
	M = repair(date.getMonth() + 1)
	d = repair(date.getDate())
	H = repair(date.getHours())
	m = repair(date.getMinutes())
	s = repair(date.getSeconds())
	w = date.getDay()
	switch (type) {
		case 'week':
			str = '星期' + '日一二三四五六'.charAt(w)
			break
		case 'time':
			str = `${y}-${M}-${d} ${H}:${m}:${s}`
			break
		default:
			str = `${y}-${M}-${d}`
			break
	}
	return str
}

/**
 * 切换月份
 * type：prev（上一个月）、next（下一个月）
 * time: 时间基准
 */
const getMonth = (type, time) => {
	if (!time) {
		time = getNow()
	}
	if (!type) {
		return time
	}
	let [y, M, d] = time.split('-')
	if (type === 'prev') {
		M = parseInt(M) - 1
		if (M === 0) {
			y = parseInt(y) - 1
			M = 12
		}
	}
	if (type === 'next') {
		M = parseInt(M) + 1
		if (M === 13) {
			y = parseInt(y) + 1
			M = 1
		}
	}
	let max = new Date(y, M, d).getDate() //获取当前日期中的月的天数
	if (d > max) {
		day = max
	}
	if (M < 10) {
		M = '0' + M
	}
	return `${y}-${M}-${d}`
}


/**
 * 多久之前
 */
const getAgo = (time) => {
	if (!time) return
	let date = Date.now() - new Date(time).getTime()
	if (date < 0) { return time }
	let y, M, d, H, m, s, k, v
	s = Math.floor(date / 1000)
	m = Math.floor(s / 60)
	H = Math.floor(m / 60)
	d = Math.floor(H / 24)
	M = Math.floor(d / 30)
	y = Math.floor(M / 12)
	if (y > 0) {
		k = 'y'
		v = y
	} else if (M > 0) {
		k = 'M'
		v = M
	} else if (d > 0) {
		k = 'd'
		v = d
	} else if (H > 0) {
		k = 'H'
		v = H
	} else if (m > 0) {
		k = 'm'
		v = m
	} else {
		k = 's'
		v = s || 1
	}
	let temp = {
		y: '%n% 年前',
		M: '%n% 个月前',
		d: '%n% 天前',
		H: '%n% 小时前',
		m: '%n% 分钟前',
		s: '%n% 秒前'
	}
	return temp[k].replace('%n%', v)
}

// 秒数转换时分秒
function convertSecondsToHMS(seconds) {
	let [hh, mm, ss] = ['00', '00', '00']
	let hours = Math.floor(seconds / 3600) // 计算小时部分
	seconds %= 3600 // 取余得到不足1小时的秒数
	let minutes = Math.floor(seconds / 60) // 计算分钟部分
	seconds %= 60 // 取余得到不足1分钟的秒数
	hh = repair(hours)
	mm = repair(minutes)
	ss = repair(seconds)
	return `${hh}:${mm}:${ss}` // 返回结果数组
}

export default {
	getNow,
	getMonth,
	getAgo
}